<?php
/**
 * | 节程 [ 节程赋能开发者，助力企业发展 ]
 * +----------------------------------------------------------------------
 *  | Copyright (c) 2020~2029 温州惊蛰网络科技有限公司 All rights reserved.
 * +----------------------------------------------------------------------
 *  | Licensed 节程并不是自由软件，未经许可不能去掉节程相关版权
 * +----------------------------------------------------------------------
 */
declare (strict_types=1);

namespace app\madmin\service;

use app\madmin\model\MallShopRule;
use app\madmin\model\Role as admin;
use app\madmin\model\RoleRule;
use app\utils\TrimData;
use think\db\Query;
use think\Exception;

class RoleService
{

    /**
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function index()
    {
        $list = admin::where('status', 1)
            ->field('id,name')
            ->select();
        return [HTTP_SUCCESS, $list];
    }

    /**
     * 查询列表
     * @param int $page
     * @param int $size
     * @param array $data
     * @return array
     * @throws \think\db\exception\DbException
     */
    public function findAll(array $data, int $page = 1, int $size = 10)
    {
//        $data =array_filter($data,function ($val){
//            if (is_array($val) || (is_string($val) && "" !=trim($val))){
//                return true;
//            }
//            return false;
//        });

        $admin = admin::field('id,name,remark,department_id,is_root,status,create_time,update_time');
        $admin = TrimData::searchDataTrim($admin, $data, ['name', 'begin_date', 'end_date']);
        $list = $admin->paginate(['page' => $page, 'list_rows' => $size]);
        return [HTTP_SUCCESS, $list];
    }

    /**
     * 保存数据
     * @param array $data
     * @return array
     */
    public function save(array $data)
    {
        $ruleList = $data['rule'];
        unset($data['rule'], $data['is_root']);
//        $shopRuleList = $data['shop_rule'];
//        unset($data['shop_rule']);

        $role = admin::create($data);
        foreach ($ruleList as $k => $v) {
            RoleRule::create(['role_id' => $role->id, 'rule_id' => $v]);
        }
//        MallShopRule::create(['role_id'=>$role->id,'rule_list' =>$shopRuleList]);

        return [HTTP_CREATED, $role];
    }

    /**
     * 读取一条数据
     * @param int $id
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function read(int $id)
    {
        $model = admin::with([
            'rule' => function (Query $query) {
                $query->where('status', 1)->visible(['id']);
            }
        ])->find($id);
        if (!$model)
            throw new Exception("角色不存在", HTTP_NOTACCEPT);
        $model = $model->toArray();
        $model['rule'] = array_column($model['rule'], 'id');

        $mallShopRule = MallShopRule::where(['role_id' => $id])->field('rule_list')->find();
        $model['shop_rule'] = $mallShopRule['rule_list'];

        return [HTTP_SUCCESS, $model];
    }

    private function getAdmin($id)
    {
        $admin = admin::find($id);
        if (1 === $admin->is_root) {
            throw new Exception("初始账号不能操作", HTTP_NOTACCEPT);
        }
    }

    /**
     * 更新数据
     * @param int $id
     * @param array $data
     * @return array
     */
    public function update(int $id, array $data)
    {

        $this->getAdmin($id);

//        $update_time = $data['update_time'];
        unset($data['update_time'], $data['is_root']);
        if (isset($data['rule']) && !empty($data['rule'])) {
            $ruleList = (array)$data['rule'];
            unset($data['rule']);

//        if (isset($data['shop_rule'])) {
//            $shopRuleList = (array)$data['shop_rule'];
//            unset($data['shop_rule']);
//            MallShopRule::update(['rule_list' => $shopRuleList], ['role_id' => $id]);
//        }
            RoleRule::where(['role_id' => $id])->delete();
            foreach ($ruleList as $k => $v) {
                RoleRule::create(['role_id' => $id, 'rule_id' => $v]);
            }
        }

        admin::where(['id' => $id, 'is_root' => 0])
            ->save($data);

        return [HTTP_CREATED, 1];
    }

    /**
     * @param $id
     * @return int
     */
    public function delete($id)
    {

        $this->getAdmin($id);

        admin::destroy(function ($query) use ($id) {
            $query->where(['id' => $id, 'is_root' => 0]);
        });
        return HTTP_NOCONTEND;
    }

}
